/**
 * 
 */
package com.monkeyboy.security.controller;

import java.util.ArrayList;
import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import com.fasterxml.jackson.annotation.JsonView;
import com.monkeyboy.security.dto.User;
import com.monkeyboy.security.entity.SocialUserInfo;

/**
 * @Description
 *
 * @author Gavin<br>
 *         2019年8月23日
 */
@RestController
public class UserController {
	@JsonView(User.UserSimpleView.class)
	@GetMapping("/user/userList") // 限制id只能为数字
	public ArrayList<User> queryUser() {
		ArrayList<User> userList = new ArrayList<User>();
		User u1 = new User("高嘉银", "111111");
		User u2 = new User("廖立晴", "222222");
		User u3 = new User("科比", "333333");
		userList.add(u1);
		userList.add(u2);
		userList.add(u3);
		return userList;
	}

	@JsonView(User.UserDetailView.class)
	@GetMapping("/user/{id:\\d+}") // 限制id只能为数字
	public User getUserInfo(@PathVariable(name = "id", required = true) String id) {
		User user = new User();
		user.setPassword("高嘉银");
		user.setPassword("123456");
		// throw new GlobalException();
		return user;
	}

	/**
	 * @Description<br>
	 * 					BindingResult和@Valid注解需要配合使用
	 * 
	 * 
	 * @Author Gavin</br>
	 *         2019年8月24日
	 */
	@PostMapping("/user/createUser")
	public User createUser(@Valid @RequestBody User user, BindingResult errors) {
		if (errors.hasErrors()) {
			errors.getAllErrors().stream().forEach(error -> {
				System.out.println(error.getDefaultMessage());
				System.out.println(error.getObjectName());
				Arrays.asList(error.getArguments()).stream().forEach(pre -> {
					System.out.println(pre);
				});
				;
			});
		}
		System.err.println(user.getUsername());
		System.err.println(user.getBirthday());
		System.err.println(user.getPassword());
		user.setId("1");
		return user;
	}

	@PutMapping("/user/updateUser/{id:\\d+}")
	public User updateUser(@Valid @RequestBody User user, BindingResult errors) {
		if (errors.hasErrors()) {
			errors.getAllErrors().stream().forEach(error -> {
				FieldError fieldError = (FieldError) error;
				String message = fieldError.getField() + ":" + fieldError.getRejectedValue() + ":"
						+ error.getDefaultMessage();
				System.err.println(message);
			});
		}
		System.err.println(user.getUsername());
		System.err.println(user.getBirthday());
		System.err.println(user.getPassword());
		return user;
	}

	@GetMapping("/user/getMe")
	public Object getMeInfo(@AuthenticationPrincipal UserDetails user) {
		// 1.
		// SecurityContextHolder.getContext().getAuthentication();获取springsecurity中的用户信息
		// 2. 通过参数 Authentication authentication获得信息
		// 3. 通过UserDetails
		return user;
	}

	@Autowired
	private ProviderSignInUtils providerSignInUtils;

	@PostMapping("/user/regist")
	public void userRegist(User user, HttpServletRequest request) {
		// 不管是注册用户还是绑定用户，都会拿到用户唯一标识,这儿就使用页面传递过来的用户名
		String userId = user.getUsername();
		System.err.println(userId);
		// 需要通过providerSignInUtils这个工具吧userId传到connection里面，然后才能插入到数据库中
		providerSignInUtils.doPostSignUp(userId, new ServletWebRequest(request));
	}

	// 可以获取到连接里面获取到的一些信息，可以在注册页面展示一些登录的第三方信息
	@GetMapping("/social/user")
	public SocialUserInfo getSocialUserInfo(HttpServletRequest request) {
		SocialUserInfo userInfo = new SocialUserInfo();
		Connection<?> connection = providerSignInUtils.getConnectionFromSession(new ServletWebRequest(request));
		userInfo.setProviderId(connection.getKey().getProviderId());
		userInfo.setProviderUserId(connection.getKey().getProviderUserId());
		userInfo.setNickname(connection.getDisplayName());
		userInfo.setHeadimg(connection.getImageUrl());
		return userInfo;
	}
}
